package com.zhongxi.guoyuan.application;

import android.app.Application;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.annotation.Nullable;

import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.entity.BaseResult;
import com.zhongxi.guoyuan.service.LocationService;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.DesTool;
import com.zhongxi.guoyuan.utils.DeviceUtils;
import com.zhongxi.guoyuan.utils.MD5Tool;
import com.zhongxi.guoyuan.utils.NetWorkUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.cookie.CookieJarImpl;
import com.zhy.http.okhttp.cookie.store.PersistentCookieStore;
import com.zhy.http.okhttp.https.HttpsUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Cache;
import okhttp3.OkHttpClient;

public class MyApplication extends Application {

    private static MyApplication instance;
    // 记录是否已经初始化
    private boolean isInit = false;

    public SharedPreferences sharedPrefrences;
    public LocationService locationService;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        if (sharedPrefrences == null) {
            sharedPrefrences = getSharedPreferences(Url.APP_SP, MODE_PRIVATE);
        }
        locationService = new LocationService(getApplicationContext());  // 百度定位
        JPushInterface.setDebugMode(false);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);            // 初始化 JPush

        UMConfigure.init(this, "58621ce9bbea833bdf00106d", "umeng", UMConfigure.DEVICE_TYPE_PHONE, "");

        //微信 wx12342956d1cab4f9, a5ae111de7d9ea137e88a5e02c07c94d
        PlatformConfig.setWeixin("wxa67785ccb81c8f81", "80ef0edd57cd28aed7be970668dc5eba");
        PlatformConfig.setQQZone("101372852", "59afd4c01cb7ff9ecc5f46a0ccd01450");


        initOkHttp(); //初始化OkHttpUtils

        new Thread(new Runnable() {
            @Override
            public void run() {
                getSocket();
            }
        }).start();

    }


    public static MyApplication getInstance() {
        return instance;
    }



    private void getSocket() {
        Socket socket = null;
        try {
            InetAddress severAddr = InetAddress.getByName("114.55.100.154");
            //应用Server的IP和端口建立Socket对象
            socket = new Socket(severAddr, 6663);
            //将信息通过这个对象来发送给Server
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())), true);
            //把用户输入的内容发送给Server
            if (socket.isConnected()) {
                String json = getJsonStr();
                out.println(json);
                out.flush();
            }
            //接收服务器信息
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //得到服务器信息
            String msg = in.readLine();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != socket)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 获取json字符串
     */
    private String getJsonStr() throws Exception {
        String jsonresult = "";//定义返回字符串
        try {
            JSONObject obj = new JSONObject();
            JSONObject objData = new JSONObject();
            objData.put("identify", DeviceUtils.getDeviceUUID(this));//设备id
            objData.put("platform", "android");
            objData.put("userid", getUserId());
            objData.put("phonebrand", android.os.Build.BRAND);//设备品牌
            objData.put("osversion", android.os.Build.VERSION.RELEASE);//设备版本号
            objData.put("majorversion", getVersionName().substring(0, 1));//api版本
            objData.put("minorversion", getVersionName().substring(2, 3));//版本号
            objData.put("network", NetWorkUtils.getNetworkState(this));//获取网络类型
            objData.put("provider", DeviceUtils.getMobileType(instance));//网络供应商
            objData.put("ip", getLocalIPAddress());//ip地址
            objData.put("province", getProvince());//省
            objData.put("city", getCity());//城市
            String now = Calendar.getInstance().getTimeInMillis() + "";
            String a = MD5Tool.sha1(now);
            String b = MD5Tool.Md5(a);
            String sourceStr = MD5Tool.Md5(MD5Tool.sha1(now));
            obj.put("id", DesTool.split(sourceStr, DeviceUtils.getDeviceUUID(this)));//设备id加密
            obj.put("now", now);
            obj.put("data", objData);
            jsonresult = obj.toString() + "\n\r\n";
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonresult;
    }

    /**
     * 纬度
     *
     * @return
     */
    public String getLatitude() {
        return sharedPrefrences.getString("latitude", "");
    }

    /**
     * 经度
     *
     * @return
     */
    public String getLongitude() {
        return sharedPrefrences.getString("longitude", "");
    }


    /**
     * 快递列表
     */
    public String getLogistics() {
        return sharedPrefrences.getString("logistics", "");
    }

    /**
     * 获取省份
     *
     * @return
     */
    public String getProvince() {
        return sharedPrefrences.getString("province", "");
    }

    /**
     * 判断是否为股东
     *
     * @return
     */
    public Boolean isShareHolders() {
        return sharedPrefrences.getBoolean("shareHolder", false);
    }

    /**
     * 判断是否为消费收益人  合伙人
     *
     * @return
     */
    public Boolean isbeneficiary() {
        return sharedPrefrences.getBoolean("beneficiary", false);
    }

    /**
     * 判断是否为商家
     *
     * @return
     */
    public Boolean ismerchants() {
        return sharedPrefrences.getBoolean("merchants", false);
    }

    /**
     * 红豆区消费金额
     *
     * @return
     */
    public String getRedzone() {
        return sharedPrefrences.getString("redzone", "0");
    }

    /**
     * 在红豆区消费多少可以成为 合伙人
     * @return
     */
    public String getShouldAmount() {
        return sharedPrefrences.getString("shouldAmount", "0");
    }

    /**
     * 判断是否为权益会员
     */
    public Boolean isPrivilege() {
        return sharedPrefrences.getBoolean("privilege", false);
    }

    /***
     *昨日红豆收益
     */
    public String totalLasRedGains() {
        return sharedPrefrences.getString("lasgains", "0");
    }

    /***
     *昨日股份分红总收益
     */
    public String totalLasMoney() {
        return sharedPrefrences.getString("lasmoney", "0");
    }

    /**
     * 股份收益(用户股份收益  股东收益+合伙人收益)
     */
    public String sharePoint() {
        return sharedPrefrences.getString("share", "0");
    }

    /**
     * 合伙人股份点数
     */
    public int partnerPoint() {
        return sharedPrefrences.getInt("point", 0);
    }

    /**
     * 是否为合伙人
     */
    public boolean isPartner() {
        return sharedPrefrences.getBoolean("partener", false);
    }

    /**
     * 获取城市
     *
     * @return
     */
    public String getCity() {
        return sharedPrefrences.getString("city", "");
    }

    /**
     * 获取店名
     *
     * @return
     */
    public String getShopName() {
        return sharedPrefrences.getString("shopname", getString(R.string.app_name));
    }

    /**
     * 获取用户名
     *
     * @return
     */
    public String getUserName() {
        return sharedPrefrences.getString("username", "");
    }
  /**
     * 获取微信用户名
     *
     * @return
     */
    public String getWxName() {
        return sharedPrefrences.getString("wxname", "");
    }
    /**
     * 获取微信用户头像
     *
     * @return
     */
    public String getWxIcon() {
        return sharedPrefrences.getString("iconurl", "");
    }

    /**
     * 获取超市默认收货人
     *
     * @return
     */
    public String getRewardName() {
        return sharedPrefrences.getString("rewardName", "");  //rewardShippingid
    }

    /**
     * 获取超市默认收货地址id
     *
     * @return
     */
    public String getRewardAddressid() {
        return sharedPrefrences.getString("rewardAddressid", "");  //rewardShippingid
    }

    /**
     * 获取超市默认手机号
     *
     * @return
     */
    public String getRewardUserPhone() {
        return sharedPrefrences.getString("rewardUserphone", "");
    }

    /**
     * 获取超市默认地址
     *
     * @return
     */
    public String getRewardAddress() {
        return sharedPrefrences.getString("rewardAddress", "");
    }

    /**
     * 获取注册时间
     *
     * @return
     */
    public String getRegisterTime() {
        return sharedPrefrences.getString("time", "");
    }

    /**
     * 获取用户头像
     *
     * @return
     */
    public String getAvatar() {
        return sharedPrefrences.getString("avatar", "");
    }


    /**
     * @return
     */
    public String getPay() {
        return sharedPrefrences.getString("pay", "");
    }

    /***豆豆兑换支付成功奖现金
     *
     * @return
     */
    public String getPayRedBean(){
        return sharedPrefrences.getString("payredbean","0");
    }

    /**
     * 美容院登录时效凭证
     *
     * @return
     */
    public String getBeautifulCredentials() {
        return sharedPrefrences.getString("beautifulcredentials", "");
    }

    /**
     * 线上赚豆商家登录时效凭证
     *
     * @return
     */
    public String getRewardCoinCredentials() {
        return sharedPrefrences.getString("rewardcoincredentials", "");
    }

    /**
     * 美豆兑换商家登录时效凭证
     *
     * @return
     */
    public String getMDChangeCredentials() {
        return sharedPrefrences.getString("MDChangecredentials", "");
    }

    /**
     * 线下赚豆商家登录时效凭证
     *
     * @return
     */
    public String getOffLineCredentials() {
        return sharedPrefrences.getString("OffLinecredentials", "");
    }

    /**
     * 获取用户人民币余额
     *
     * @return
     */
    public String getRmb() {
        return sharedPrefrences.getString("rmb", "0");
    }

    /**
     * 获取用户银币余额
     *
     * @return
     */
    public String getSilver() {
        return sharedPrefrences.getString("silver", "0");
    }

    /**
     * 获取用户美豆余额
     *
     * @return
     */
    public String getInnerCurrency() {
        return sharedPrefrences.getString("inner", "0");
    }

    /**
     * 获取用户红豆余额
     *
     * @return
     */
    public String getHdCurrency() {
        return sharedPrefrences.getString("hd", "0");
    }


    /**
     * 获取用户id
     *
     * @return
     */
    public String getUserId() {
        return sharedPrefrences.getString("userid", "");
    }

    /**
     * 获取 商户邀请码
     *
     * @return
     */
    public String getMerchantsCode() {
        return sharedPrefrences.getString("merchantsCode", "");
    }


    /**
     * 获取校验用的随机8位字符串
     *
     * @return
     */
    public String getSk() {
        return sharedPrefrences.getString("sk", "79563421");
    }

    /**
     * 获取时间戳
     *
     * @return
     */
    public String getNow() {

        return sharedPrefrences.getString("now", "").toString().trim();
    }

    /**
     * 获取手机号
     *
     * @return
     */
    public String getPhone() {
        return sharedPrefrences.getString("phone", "");
    }

    /**
     * 获取msgid
     *
     * @return
     */
    public String getMsgid() {
        return sharedPrefrences.getString("msgid", "");
    }


    /**
     * 微信登录返回的id
     *
     * @return
     */
    public String getAppOpenid() {
        return sharedPrefrences.getString("appopenid", "");
    }

    /**
     * 获取聊天对方的头像URL
     *
     * @return
     */
    public String getChatAvatar() {
        return sharedPrefrences.getString("from_avater", "");
    }

    /**
     * 获取聊天对方的昵称
     *
     * @return
     */
    public String getNiCheng() {
        return sharedPrefrences.getString("from_nicheng", "");
    }

    /**
     * 美容院聊天的id
     *
     * @return
     */
    public String getChatId() {
        return sharedPrefrences.getString("chatId", "");
    }

    /**
     * 消费商家的电话
     *
     * @return
     */
    public String getShopPhone() {
        return sharedPrefrences.getString("shopPhone", "");
    }

    /**
     * 消费商家店名
     *
     * @return
     */
    public String getShopNick() {
        return sharedPrefrences.getString("shopName", "");
    }

    /**
     * 获取消费商家图标
     *
     * @return
     */
    public String getShopImage() {
        return sharedPrefrences.getString("shopImage", "");
    }

    /**
     * 获取用户红豆余额
     */
    public String getRedBean() {
        return sharedPrefrences.getString("redbean", "0.00");
    }

    /**
     * 微信支付会调用
     */
    public String getWinXinMD() {
        return sharedPrefrences.getString("weixinMD", "0.00");
    }

    /**
     * 微信支付会调用
     */
    public String getWinXinHD() {
        return sharedPrefrences.getString("weixinHD", "0.00");
    }

    /**
     * 当面付失败获取orderid
     */
    public String getQrPayFailOrderId() {
        return sharedPrefrences.getString("orderId", "");
    }

    /**
     * 当面付失败获取  certificate
     */
    public String getQrPayFailCertificate() {
        return sharedPrefrences.getString("certificate", "");
    }

    public String getImei() {
        return sharedPrefrences.getString("szImei", "");
    }

    public String getUrl() {
        String utoken = "";
        String desid = "";
        try {
            if (getUserId() != null && !"".equals(getUserId())) {
                String sourcestr = MD5Tool.Md5(MD5Tool.sha1(getNow()) + getSk());
                desid = URLEncoder.encode(DesTool.split(sourcestr, getUserId()), "UTF-8");   //修改编码
                desid = URLEncoder.encode(desid, "UTF-8");   //修改编码
                utoken = MD5Tool.Md5(getUserId() + getPhone() + getNow());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return desid + "/" + utoken + "/" + getSk() + "/" + getNow() + "/" + getImei() + ".llm";
    }

    /**
     * 接口拼接校验码
     *
     * @return
     */
    public String getCheck(boolean isUser) {
        String params = null;
        try {
            String sourcestr = MD5Tool.Md5(MD5Tool.sha1(getNow()) + getSk());
            if (isUser) {
                params = URLEncoder.encode(DesTool.split(sourcestr, "userid=" + getUserId()
                        + "&clientvar=" + getVersionName().substring(0, 3) + "&card=" + getImei() + "&beauty_console=" + getBeautifulCredentials()
                        + "&market_console=" + getRewardCoinCredentials() + "&exchange_console=" + getMDChangeCredentials() + "&offlinemarket_console=" + getOffLineCredentials()), "UTF-8");
            } else {
                params = URLEncoder.encode(DesTool.split(sourcestr, "userid=" + getUserId() + "&clientvar=" + getVersionName().substring(0, 3) + "&card=" + getImei()), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return params;
    }

    /**
     * 对字符串des加密，并对加密字符串中特殊字符转义
     *
     * @param str
     * @return
     */
    public String descsc(String str) {
        String sourcestr = MD5Tool.Md5(MD5Tool.sha1(getNow()) + getSk());
        try {
            return URLEncoder.encode(DesTool.split(sourcestr, str), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 返回当前程序版本号
     */
    public int getVersionCode() {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        int version = packInfo.versionCode;
        return version;
    }

    public String getMinVersion() {
        String versionName = "";
        PackageManager packageManager = getPackageManager();
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(getPackageName(), 0);
            versionName = packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName.substring(versionName.length() - 1, versionName.length());
    }

    public String getVersionName() {
        String versionName = "";
        PackageManager packageManager = getPackageManager();
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(getPackageName(), 0);
            versionName = packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 获取当前ip地址
     *
     * @return
     */
    @Nullable
    public String getLocalIPAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void setSpValue(BaseResult baseResult) {
        try {
            if (baseResult != null && !"".equals(baseResult)) {
                sharedPrefrences.edit().putString("now", baseResult.getNow()).commit();
                sharedPrefrences.edit().putString("sk", baseResult.getSafestring()).commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析后台返回的加密数据
     *
     * @param securityKey
     */
    public String parseSecutiryKey(String securityKey) {
        String jsonStr = "";
        try {
            String sourcestr = MD5Tool.Md5(getSk() + getNow());
            String str = URLDecoder.decode(securityKey, "UTF-8");
            jsonStr = DesTool.splitdecode(sourcestr, str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonStr;
    }

    /**
     * @Description 初始化OkHttp
     */
    private void initOkHttp() {
        File cache = getExternalCacheDir();
        int cacheSize = 10 * 1024 * 1024;
        CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(getApplicationContext()));
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .addInterceptor(new LoggerInterceptor("TAG"))
                .connectTimeout(10000L, TimeUnit.MILLISECONDS)  // 连接超时(单位:秒)
                .readTimeout(10000L, TimeUnit.MILLISECONDS)    //读取超时(单位:秒)
                .cache(new Cache(cache.getAbsoluteFile(), cacheSize))//设置缓存
                .cookieJar(cookieJar)
                .hostnameVerifier(new HostnameVerifier() {    //无视Https证书是不是正确的
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                //其他配置
                .build();

        OkHttpUtils.initClient(okHttpClient);
    }
}